package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.module;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import com.iwhalecloud.bss.kite.cucc.service.util.ProdCateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.bss.kite.client.vo.scene.ModuleVO;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.ContractModuleVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.ContractRelVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.SceneNewOfferSeneVO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.service.batch.BatchAcceptUtil;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.spec.impl.transfer.GoodsInfoTransfer;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInstContract;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.AcceptContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.SceneModule;
import com.iwhalecloud.bss.kite.web.service.accept.handler.module.AbstractModuleHandler;

/**
 * 合同信息
 */
@Service
public class ContractRelInfoModuleHandler extends AbstractModuleHandler {

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    IOperateSceneInstService operateSceneInstService;

    @Override
    public List<? extends ModuleVO> execute(AcceptContext context, SceneModule sceneModule) {

        SceneNewOfferSeneVO sceneAccountInfoVo = (SceneNewOfferSeneVO) context.getSceneVo();
        ContractModuleVO contractModuleVO = getContractModule(context, Boolean.FALSE);
        sceneAccountInfoVo.setContract(contractModuleVO);

        return Collections.singletonList(contractModuleVO);
    }

    @Override
    public List<ModuleVO> previewSceneVo(AcceptContext context, SceneModule sceneModule) {

        SceneNewOfferSeneVO sceneNewOfferSeneVO = (SceneNewOfferSeneVO) context.getSceneVo();
        ContractModuleVO contractModuleVO = getContractModule(context, Boolean.TRUE);
        contractModuleVO.setIsEdit(LocalKeyConsts.IFTRUE_F);
        sceneNewOfferSeneVO.setContract(contractModuleVO);

        return Collections.singletonList(contractModuleVO);
    }

    private ContractModuleVO getContractModule(AcceptContext context, Boolean isPreview) {
        String sceneInstId = context.getSceneVo().getSceneInstId();
        // 批量受理当前修改销售品实例标识，存在则说明是批量受理的单个修改场景
        String curOfferInstId = context.getAcceptRequest().getCurOfferInstId();
        List<ContractRelVO> contractRels = new ArrayList<>();
        KiteSceneInst sceneInst = this.querySceneInstService.getSceneInst(sceneInstId);
        String rootInstId = sceneInst.getRootInstId();
        KiteOfferInst offerInst = querySceneInstService.getOfferInst(sceneInst.getCustId(), rootInstId);
        // 批量受理的单个修改，只处理当前修改的销售品实例
        if (KiteStringUtils.isNotEmpty(curOfferInstId)) {
            offerInst = querySceneInstService.getOfferInst(sceneInst.getCustId(), curOfferInstId);
        }
        String cateId = Optional.ofNullable(offerInst.getAttr("cateId")).map(KiteAttr::getDefaultValue).orElse("");
        if(KiteStringUtils.isEmpty(cateId)){
            cateId = CuccPosServiceUtils.getCateId(sceneInstId, sceneInst.getCustId());
        }
        if(KiteStringUtils.isEmpty(cateId)){
            KiteInst inst = querySceneInstService
                .getKiteInst(KiteWebContext.getContext().getCustId(), InstType.MAIN_OFFER_INST,
                    rootInstId);
            if (KiteObjectUtils.isEmpty(inst)) {
                inst = querySceneInstService.getKiteInst(KiteWebContext.getContext().getCustId(), InstType.GIFT_OFFER_INST,
                    rootInstId);
            }
            String offerId = inst.getSpecId();
            Offer offer = OfferCache.get(offerId);
            cateId = offer.getCateId();
        }
        if (!GoodsInfoTransfer.isAddRoleOffer(offerInst.getSpecId(), cateId)) {
            List<KiteOfferInstContract> kiteOfferInstContractRelList = querySceneInstService.listOfferInstContracts(context.getAcceptRequest().getCustId(), offerInst.getOfferInstId());
            // 过滤掉动作为D的
            kiteOfferInstContractRelList.removeIf(kiteOfferInstContractRel-> KiteStringUtils.isEqual(kiteOfferInstContractRel.getActionType().name(), ActionType.D.name()));
            if (KiteListUtils.isNotEmpty(kiteOfferInstContractRelList)) {
                for (KiteOfferInstContract kiteOfferInstContractRel : kiteOfferInstContractRelList) {
                    ContractRelVO contractRel = new ContractRelVO();
                    contractRel.setContractId(kiteOfferInstContractRel.getContractBatchId());
                    contractRel.setContractNo(kiteOfferInstContractRel.getContractNo());
                    contractRel.setContractName(kiteOfferInstContractRel.getContractName());
                   /* String contractUrl = kiteOfferInstContractRel.getContractUrl();
                    String attachmentName = kiteOfferInstContractRel.getAttachmentName();
                    if (KiteStringUtils.isNotEmpty(attachmentName)) {
                        contractRel.setFileId(KiteStringUtils.join(contractUrl, "*_*", attachmentName));
                    }
                    else {
                        contractRel.setFileId(contractUrl);
                    }*/
                    List<com.iwhalecloud.bss.kite.cucc.client.dto.order.ContAttachmentDTO> attachment= new ArrayList<>();
                    String oldattachment = JSONObject.toJSONString(kiteOfferInstContractRel.getAttachments());
                    attachment=JSONObject.parseArray(oldattachment, com.iwhalecloud.bss.kite.cucc.client.dto.order.ContAttachmentDTO.class);
                    contractRel.setAttachments(attachment);
                    contractRel.setOfferInstId(kiteOfferInstContractRel.getOfferInstId());
                    contractRel.setOfferName(Optional.ofNullable(OfferCache.get(offerInst.getSpecId())).map(Offer::getOfferName).orElse(""));
                    contractRel.setInstId(kiteOfferInstContractRel.getInstId());
                    contractRel.setOfferInstContractRelId(kiteOfferInstContractRel.getOfferObjInstRelId());
                    contractRel.setChangeShowDelete("F");
                    contractRels.add(contractRel);
                }
            }
            else {
                ContractRelVO contractRel = new ContractRelVO();
                contractRel.setOfferInstId(offerInst.getOfferInstId());
                contractRel.setOfferName(offerInst.getOfferName());
                contractRels.add(contractRel);
            }
        }
        List<ContractRelVO> oldContractRelVOList = (List<ContractRelVO>) querySceneInstService
            .getExtParameter(sceneInstId).get(sceneInstId + "_CONTRACTRELVO");
        if (isPreview) { // 预览
            String busiChangeScene = querySceneInstService
                .getExtParameterValue(context.getSceneVo().getSceneInstId(), LocalKeyConsts.BUSI_CHANGE_SCENE);
            if (KiteListUtils.isNotEmpty(oldContractRelVOList) && KeyConsts.IFTRUE_T.equals(busiChangeScene)) {
                ContractRelVO contractRelVO = oldContractRelVOList.get(0);
                contractRels.stream().forEach(contractRel -> {
                    if (!KiteStringUtils.isEqual(contractRel.getContractId(), contractRelVO.getContractId())) {
                        contractRel.setOldContractId(contractRelVO.getContractId());
                    }
                    if (!KiteStringUtils.isEqual(contractRel.getContractNo(), contractRelVO.getContractNo())) {
                        contractRel.setOldContractNo(contractRelVO.getContractNo());
                    }
                    if (!KiteStringUtils.isEqual(contractRel.getContractName(), contractRelVO.getContractName())) {
                        contractRel.setOldContractName(contractRelVO.getContractName());
                    }
                    if (!KiteStringUtils.isEqual(contractRel.getFileId(), contractRelVO.getFileId())) {
                        contractRel.setOldContractUrl(contractRelVO.getFileId());
                    }
                    if (!KiteStringUtils.isEqual(contractRel.getOfferInstId(), contractRelVO.getOfferInstId())) {
                        contractRel.setOldOfferInstId(contractRelVO.getOfferInstId());
                    }
                    if (!KiteStringUtils.isEqual(contractRel.getOfferName(), contractRelVO.getOfferName())) {
                        contractRel.setOldOfferName(contractRelVO.getOfferName());
                    }
                });
            }
        } else { // 初始化
            operateSceneInstService.putExtParameter(sceneInstId, sceneInstId + "_CONTRACTRELVO", contractRels);
        }
        ContractModuleVO contractModuleVO = new ContractModuleVO();
        if (KiteListUtils.isNotEmpty(oldContractRelVOList)) {
            if (oldContractRelVOList.size() > 1) {
                ContractRelVO contractRelVO = oldContractRelVOList.get(0);
                contractRels = contractRels.stream().filter(v -> (!KiteStringUtils.isEqual(v.getContractId(), contractRelVO.getContractId()))).collect(Collectors.toList());
            }
        }
        contractModuleVO.setContractRelInfo(contractRels);
        // 批量受理部分环节，不允许编辑
        if (BatchAcceptUtil.isBatchNode(context.getAcceptRequest().getSceneInstId())
            || BatchAcceptUtil.batchNodeResetIsEdit(context.getAcceptRequest().getSceneInstId())) {
            contractModuleVO.setIsEdit("F");
        }
        if(KiteStringUtils.equalsAny(cateId,ProdCateUtil.getDoubleLineCateIdForArr())){
            contractModuleVO.setProdFlag("SX");
        }
        contractModuleVO.setCateId(cateId);
        return contractModuleVO;
    }
}
